// 将localStorage中的token添加到所有请求中的header中
$(document).ajaxSend(function (event, xhr, options) {
    xhr.setRequestHeader("user_token", localStorage.getItem("userToken"))
})

// 当后端响应失败时执行下面的代码
$(document).ajaxError(function (event, xhr, options) {
    if (xhr.status == 401) {
        alert('用户未登录！')
        location.href = '../blog_login.html'
    }
})


// 根据url来获取相应的用户信息
function getUserInfo(url) {
    $.ajax({
        type: 'get',
        url: url,
        success: function (ret) {
            if (ret != null && ret.code == 'SUCCESS' && ret.data != null) {
                $(".left .card h3").text(ret.data.userName);
                $(".left .card a").attr("href",ret.data.githubUrl);
                let url = ret.data.githubUrl.substring(0, 10) + '...'
                $(".left .card a").text('@gitee:' + url)
                $("#userAvatar").attr('src', ret.data.avatarPath)
                $("#articleNums").text(ret.data.articleNums)
                // 将用户id存入头像的img标签中, 方便后续实现点击头像将用户的id传进去
                document.getElementById("userAvatar").setAttribute("userId", ret.data.id);
            }
        }
    })
}

//用户注销
function logout() {
    localStorage.removeItem('userToken')
    localStorage.removeItem('loginUserId')
    location.href = '../blog_login.html'
}


// 绑定点击事件,实现点击头像后跳转到对应用户的详情页
function clickAvatar() {
    document.getElementById('userAvatar').addEventListener('click', () => {
        // 获取当前用户ID
        let currentUserId = document.getElementById('userAvatar').getAttribute('userId');
        // 跳转到用户详情页（URL格式：user_detail.html?userId=currentUserId）
        window.location.href = `user_detail.html?userId=${currentUserId}`;
    });
}

// 通过userId来查询这个用户都发布了哪些文章
function BlogsOfUser(userId) {
    $.ajax({
        type: 'get',
        url: 'blog/getBlogsOfUser?userId='+userId,
        success: function (ret) {
            if (ret.code == 'SUCCESS' && ret.data != null && ret.data.length > 0) {
                let blogsContainer  = document.querySelector('.right .content');
                let finalHtml = ''
                for (let blog of ret.data) {
                    // 用正则表达式移除Markdown符号（**、## 等）
                    let rawContent = blog.content
                        .replace(/\*\*/g, '')   // 去除加粗符号
                        .replace(/#{1,6}\s?/g, '') // 去除标题符号（#、##等）
                        .replace(/`/g, '');     // 去除代码块符号

                    let content = rawContent.substring(0, 100) + '...'
                    finalHtml += `
                            <div class="blog">
                                <div class="title">${blog.title}</div>
                                <div class="date">${blog.createTime}</div>
                                <div class="desc">${content}</div>
                                <a class="detail" href="blog_detail.html?blogId=${blog.id}">查看全文&gt;&gt;</a>
                            </div>`;
                }
                blogsContainer .innerHTML = finalHtml
            }
        }
    })
}